package edu.luc.etl.android;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import edu.luc.etl.xml.FeedList;
import edu.luc.etl.xml.FeedListHandler;
import edu.luc.etl.xml.FeedListItem;

public class SelectFeed extends Activity implements OnItemClickListener{
	private FeedList feed = null;
	private FeedListHandler theHandler;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_feed);
		
		
		Bundle extras = getIntent().getExtras();
		feed = getFeed(extras.getString("url"));
		UpdateDisplay();
	}
	
	private void UpdateDisplay()
    {
       
		ListView itemlist = (ListView) findViewById(R.id.itemlist);

        ArrayAdapter<FeedListItem> adapter = new ArrayAdapter<FeedListItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems());

        itemlist.setAdapter(adapter);
        
        itemlist.setOnItemClickListener(this);
        
        itemlist.setSelection(0);
        
    }
	
	
	public FeedList getFeed(String urlToRssFeed)
    {

		try
        {
            // setup the url
           URL url = new URL(urlToRssFeed);

           // create the factory
           SAXParserFactory factory = SAXParserFactory.newInstance();
           // create a parser
           SAXParser parser = factory.newSAXParser();

           // create the reader (scanner)
           XMLReader xmlreader = parser.getXMLReader();
           // instantiate our handler
           theHandler = new FeedListHandler();
           // assign our handler
           xmlreader.setContentHandler(theHandler);
           // get our data through the url class
           InputSource is = new InputSource(url.openStream());
           // perform the synchronous parse           
           xmlreader.parse(is);
           // get the results - should be a fully populated RSSFeed instance, 
		   // or null on error
           
           return theHandler.getFeed();
        }
        catch (Exception ee)
        {
            // if you have a problem, simply return null
            return null;
        }
    }
	public void onItemClick(AdapterView parent, View v, int position, long id)
    {
	   
				Intent i = new Intent(this, Home.class);
	    	 	startActivity(i);
	     
    }
}
